<template>
  <page-container title="测试列表" :showBack="true">
    <template v-slot:nav-left>
      <view class="nav-left">
        <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
      </view>
    </template>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="!isPageReady">
      <view class="loading-text">页面加载中...</view>
    </view>

    <!-- 固定按钮区域（在导航栏下方） -->
    <view class="fixed-button-area" v-if="isPageReady" :style="{ top: navBarHeight + statusBarHeight + 'px' }">
      <view class="settled-order-btn" @click="goToSettledOrders">
        <text class="btn-text">已结算订单{{navBarHeight + 'px' }}</text>
      </view>
    </view>

    <scroll-view class="scroll-container" 
        v-if="isPageReady" 
        :style="{ height: 'calc(100vh - ' + navBarHeight + 'px)', paddingTop: navBarHeight + 20 + 'px'}" 
        scroll-y="true" 
        refresher-enabled="true" 
        :refresher-triggered="refreshing" 
        @refresherrefresh="onRefresh"
        :refresher-threshold="45" 
        refresher-default-style="black" 
        refresher-background="#f5f5f6">
      <!-- 列表内容 -->
      <view class="list-container">
        <view class="list-item" v-for="(item, index) in listData" :key="index" @click="onItemClick(item)">
          <view class="item-header">
            <text class="item-title">{{ item.title }}</text>
            <text class="item-status" :class="item.status">{{ item.statusText }}</text>
          </view>
          <view class="item-content">
            <text class="item-desc">{{ item.description }}</text>
          </view>
          <view class="item-footer">
            <text class="item-time">{{ item.createTime }}</text>
            <text class="item-amount" v-if="item.amount">¥{{ item.amount }}</text>
          </view>
        </view>


        <!-- 空状态 -->
        <view class="empty-state" v-if="listData.length === 0">
          <text class="empty-text">暂无订单数据</text>
        </view>
      </view>
    </scroll-view>
  </page-container>
</template>

<script>
import { checkLogin } from '@/utils/auth'

export default {
  name: 'ListPage',
  data() {
    return {
      listData: [],
      refreshing: false,
      navBarHeight: 88, // 导航栏高度，动态计算
      statusBarHeight: 0, // 状态栏高度
      isPageReady: false // 页面是否准备就绪
    }
  },
  onLoad() {
    this.loadData()
  },
  onReady() {
    // 页面渲染完成后计算导航栏高度
    this.$nextTick(() => {
      // 延迟一点时间确保胶囊按钮信息完全加载
      setTimeout(() => {
        this.calculateNavBarHeight()
        this.isPageReady = true
      }, 100)
    })
  },
  onShow() {
    // 页面显示时刷新数据
    this.loadData()
  },
  methods: {
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadData().finally(() => {
        console.log('onRefresh')

        this.refreshing = false
      })
    },

    // 加载数据
    async loadData() {
      console.log('loadData');

      try {
        // 模拟API请求 - 一次性加载所有数据
        const mockData = this.getMockData()
        this.listData = mockData

        // 实际项目中，这里应该调用真实的API
        // const res = await this.$http.get('/api/list')
        // this.listData = res.data || []

      } catch (error) {
        console.error('加载数据失败:', error)
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        })
      }
    },

    // 模拟数据
    getMockData() {
      const statusList = [
        { status: 'pending', statusText: '待处理' },
        { status: 'processing', statusText: '处理中' },
        { status: 'completed', statusText: '已完成' },
        { status: 'cancelled', statusText: '已取消' }
      ]

      const data = []
      const totalCount = 20 // 一次性生成20条数据

      for (let i = 0; i < totalCount; i++) {
        const statusItem = statusList[i % statusList.length]

        data.push({
          id: i + 1,
          title: `订单项目 ${i + 1}`,
          description: `这是第${i + 1}个订单的详细描述信息，包含了订单的基本信息和处理状态。`,
          status: statusItem.status,
          statusText: statusItem.statusText,
          createTime: this.formatTime(new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000)),
          amount: (Math.random() * 10000 + 1000).toFixed(2)
        })
      }

      return data
    },

    // 格式化时间
    formatTime(date) {
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (24 * 60 * 60 * 1000))

      if (days === 0) {
        return '今天'
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    },

    // 点击列表项
    onItemClick(item) {
      uni.showToast({
        title: `点击了: ${item.title}`,
        icon: 'none'
      })

      // 实际项目中可以跳转到详情页
      // uni.navigateTo({
      //   url: `/pages/detail/index?id=${item.id}`
      // })
    },

    // 跳转到已结算订单页面
    goToSettledOrders() {
      uni.showToast({
        title: '跳转到已结算订单页面',
        icon: 'none'
      })

      // 实际项目中可以跳转到已结算订单页面
      // uni.navigateTo({
      //   url: '/pages/order/settledOrder'
      // })
    },

    // 动态计算导航栏高度
    calculateNavBarHeight() {
      try {
        // 获取系统信息
        const systemInfo = uni.getSystemInfoSync()
        this.statusBarHeight = systemInfo.statusBarHeight || 0

        // #ifdef MP-WEIXIN
        // 小程序模式下，获取胶囊按钮信息来精确计算导航栏高度
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
        console.log('胶囊按钮信息:', menuButtonInfo)

        if (menuButtonInfo && menuButtonInfo.top > 0 && menuButtonInfo.height > 0) {
          // 导航栏高度 = 胶囊底部到状态栏底部的距离 + 安全边距
          this.navBarHeight = menuButtonInfo.top - this.statusBarHeight + menuButtonInfo.height + 8
          console.log('使用胶囊信息计算导航栏高度:', this.navBarHeight)
        } else {
          // 胶囊信息获取失败，使用更准确的默认计算
          // 在小程序中，导航栏通常是44px，加上状态栏高度
          this.navBarHeight = this.statusBarHeight + 44
          console.log('胶囊信息获取失败，使用默认计算导航栏高度:', this.navBarHeight)
        }
        // #endif

        // #ifndef MP-WEIXIN
        // 非小程序模式，使用标准计算
        this.navBarHeight = this.statusBarHeight + 44

        // 如果是iPhone X及以上设备，需要加上安全区域
        if (systemInfo.model && systemInfo.model.includes('iPhone')) {
          if (systemInfo.safeAreaInsets) {
            this.navBarHeight += systemInfo.safeAreaInsets.top || 0
          }
        }
        // #endif

        console.log('状态栏高度:', this.statusBarHeight)
        console.log('导航栏总高度:', this.navBarHeight)
        console.log('按钮区域top值:', this.navBarHeight + 'px')

      } catch (error) {
        console.error('获取系统信息失败:', error)
        // 使用默认值
        this.navBarHeight = 88
        this.statusBarHeight = 20
      }
    }
  }
}
</script>

<style scoped lang="scss">
/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f5f5f6;

  .loading-text {
    font-size: 28rpx;
    color: #999999;
  }
}

.scroll-container {
  background-color: #f5f5f6;
}

/* 固定按钮区域（在导航栏下方） */
.fixed-button-area {
  position: fixed;
  left: 0;
  right: 0;
  z-index: 1000;
  padding: 20rpx 20rpx 10rpx 20rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #eeeeee;
  transition: top 0.3s ease;
}

/* 已结算订单按钮样式 */
.settled-order-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #666666;
  border-radius: 8rpx;
  padding: 16rpx 32rpx;
  transition: all 0.2s ease;
  border: 1rpx solid rgba(212, 175, 55, 0.3);

  &:active {
    transform: scale(0.95);
    background-color: #555555;
  }

  .btn-text {
    font-size: 26rpx;
    color: #d4af37;
    font-weight: 500;
    white-space: nowrap;
  }
}

.list-container {
  padding-left: 20rpx;
  padding-right: 20rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  /* 备用方案：为不支持safe-area的设备提供额外间距 */
  padding-bottom: calc(20rpx + 40rpx);
  transition: padding-top 0.3s ease;
}

.list-item {
  background-color: #ffffff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;

  &:active {
    transform: scale(0.98);
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.item-title {
  font-size: 32rpx;
  color: #0B1F20;
  font-weight: 500;
  flex: 1;
}

.item-status {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;

  &.pending {
    background-color: #fff3cd;
    color: #856404;
  }

  &.processing {
    background-color: #d1ecf1;
    color: #0c5460;
  }

  &.completed {
    background-color: #d4edda;
    color: #155724;
  }

  &.cancelled {
    background-color: #f8d7da;
    color: #721c24;
  }
}

.item-content {
  margin-bottom: 20rpx;
}

.item-desc {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-time {
  font-size: 24rpx;
  color: #999999;
}

.item-amount {
  font-size: 28rpx;
  color: #d4af37;
  font-weight: 500;
}


.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;

  .empty-text {
    font-size: 28rpx;
    color: #999999;
  }
}

/* 动画效果 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
